﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OL.FrameCore.WebUI.Code
{
    public class VisitFilterAttribute : Attribute, IActionFilter
    {
        ILogger logger = LogManager.GetCurrentClassLogger();
        private readonly IHttpContextAccessor _httpContextAccessor;

        public VisitFilterAttribute(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var page = context.HttpContext.Request.Path.Value;
            string ua = context.HttpContext.Request.Headers["User-Agent"];
            //string ip = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString();
            string ip = this._httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
            string re = context.HttpContext.Request.Headers["Referer"];
            string host = context.HttpContext.Request.Host.Value ?? "";

            //长度处理
            if (page.Length > 250)
            {
                page = page.Substring(0, 250);
            }
            if (string.IsNullOrEmpty(ua) == false && ua.Length > 250)
            {
                ua = ua.Substring(0, 250);
            }
            if (string.IsNullOrEmpty(re) == false && re.Length > 250)
            {
                re = re.Substring(0, 250);
            }

            var visitModel = new Visit
            {
                ip = ip,
                ua = ua ?? "",
                visit_page = page,
                visit_time = DateTime.Now,
                referer = re ?? "",
                host = host,
            };


            Task.Factory.StartNew(obj =>
            {
                Visit visit = (Visit)obj;
                try
                {
                    logger.Info($"page:{visit.visit_page} IP:{visit.ip}  UA:{visit.ua} Referer:{visit.referer} Host:{visit.host}");

                    //_visitService.Insert(visit);
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    //throw;
                }
            }, visitModel);

        }
    }

    public class Visit
    {
        public string ip { get; set; }
        public string ua { get; set; }
        public string visit_page { get; set; }
        public DateTime visit_time { get; set; }
        public string referer { get; set; }
        public string host { get; set; }
    }
}
